<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择类型" clearable>
          <el-option
            v-for="type in types"
            :key="type.id"
            :label="type.typeName"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商户ID" prop="mchId">
        <el-input
          v-model="queryParams.mchId"
          placeholder="请输入所属商户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入标签"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章分类" prop="contentCategory">
        <el-select v-model="queryParams.contentCategory" placeholder="请选择文章分类" clearable>
          <el-option
            v-for="dict in dict.type.content_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择文章类型" clearable>
          <el-option
            v-for="dict in dict.type.content_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章门类" prop="contentClass">
        <el-select v-model="queryParams.contentClass" placeholder="请选择文章门类" clearable>
          <el-option
            v-for="dict in dict.type.content_class"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="删除标识" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="请选择删除标识" clearable>
          <el-option
            v-for="dict in dict.type.tf"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="daterangeSendTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:content:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:content:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:content:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:content:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" width="300" show-overflow-tooltip />
      <el-table-column label="分类ID" align="center" prop="typeId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="type in types">
            <span v-if="type.id == scope.row.typeId">
              {{type.typeName}}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="缩略图" align="center" prop="scaleImg">
        <template slot-scope="scope">
          <el-image :src="scope.row.scaleImg"
                    :preview-src-list="evaluatePictureList"
                    @mouseover="showPicture(scope.row.scaleImg)"
                    :style="{ width: '60px', height: '60px' }"/>
        </template>
      </el-table-column>
      <el-table-column label="商户ID" align="center" prop="mchId" />
      <el-table-column label="标签" align="center" prop="tags" width="120" show-overflow-tooltip/>
      <el-table-column label="内容" align="center" prop="content" width="300" show-overflow-tooltip  />
      <el-table-column label="文章分类" align="center" prop="contentCategory">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.content_category" :value="scope.row.contentCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="文章类型" align="center" prop="contentType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.content_type" :value="scope.row.contentType"/>
        </template>
      </el-table-column>
      <el-table-column label="文章分类" align="center" prop="contentClass">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.content_class" :value="scope.row.contentClass"/>
        </template>
      </el-table-column>
      <el-table-column label="发布人ID" align="center" prop="userId" />
      <el-table-column label="权重" align="center" prop="weight" />
<!--      <el-table-column label="留言、提问，目标用户ID" align="center" prop="toUserId" />-->
      <el-table-column label="删除标识" align="center" prop="delFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tf" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注字段" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:content:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:content:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内容对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin: 20px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="分类ID" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="商户ID" prop="mchId">
          <el-input v-model="form.mchId" placeholder="默认1" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="多个以逗号分隔" />
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input v-model="form.weight" placeholder="0-100，越大排序约靠前" />
        </el-form-item>
        <el-form-item label="缩略图" prop="scaleImg">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :on-change="uploadImg"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
          </el-upload>
          <div v-if="form.scaleImg">
            <el-image
              :src="form.scaleImg"
              title="点击查看图片"
              :preview-src-list="evaluatePictureList"
              @mouseover="showPicture(form.scaleImg)"
              :style="{ width: '80px', height: '85px' }"
              fit="scale-down"
              show-overflow-tooltip="false"
            />
          </div>
        </el-form-item>
        <el-form-item label="文章分类" prop="contentCategory">
          <el-select v-model="form.contentCategory" placeholder="请选择文章分类">
            <el-option
              v-for="dict in dict.type.content_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章类型" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择文章类型">
            <el-option
              v-for="dict in dict.type.content_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章门类" prop="contentClass">
          <el-select v-model="form.contentClass" placeholder="请选择文章门类">
            <el-option
              v-for="dict in dict.type.content_class"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="备注字段" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注字段" />
        </el-form-item>
      </el-form>
      <div style="float: right; margin-bottom: 30px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listContent, getContent, delContent, addContent, updateContent } from "@/api/article/content";
import {upload} from "@/api/common";
import {allType} from "@/api/article/type";

export default {
  name: "Content",
  dicts: ['content_category', 'content_type', 'content_class', 'tf'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内容表格数据
      contentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文章类型
      types: [],
      // 备注字段时间范围
      daterangeSendTime: [],
      // 备注字段时间范围
      daterangeCreateTime: [],
      // 备注字段时间范围
      daterangeUpdateTime: [],
      // 缩略图数据
      evaluatePictureList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        typeId: null,
        scaleImg: null,
        mchId: null,
        content: null,
        contentCategory: null,
        contentType: null,
        contentClass: null,
        userId: null,
        toUserId: null,
        tags: null,
        delFlag: null,
        sendTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "分类ID不能为空", trigger: "blur" }
        ],
        scaleImg: [
          { required: true, message: "缩略图不能为空", trigger: "blur" }
        ],
        mchId: [
          { required: true, message: "所属商户ID不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        contentCategory: [
          { required: true, message: "文章分类，'pub'-发布, 'message'-留言, 'ask'-问答不能为空", trigger: "change" }
        ],
        contentType: [
          { required: true, message: "文章类型，normal-正常、img-图文、video-视频不能为空", trigger: "change" }
        ],
        contentClass: [
          { required: true, message: "文章分类，normal-正常、pay-收费不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getAllTypes();
    this.getList();
  },
  methods: {
    /** 查询内容列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeSendTime && '' != this.daterangeSendTime) {
        this.queryParams.params["beginSendTime"] = this.daterangeSendTime[0];
        this.queryParams.params["endSendTime"] = this.daterangeSendTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listContent(this.queryParams).then(response => {
        this.contentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        typeId: null,
        scaleImg: null,
        mchId: null,
        content: null,
        contentCategory: 'pub',
        contentType: 'normal',
        contentClass: 'normal',
        weight: 0,
        userId: null,
        toUserId: null,
        tags: null,
        delFlag: null,
        sendTime: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSendTime = [];
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改内容";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除内容编号为"' + ids + '"的数据项？').then(function() {
        return delContent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/content/export', {
        ...this.queryParams
      }, `content_${new Date().getTime()}.xlsx`)
    },
    /** 上传 */
    uploadImg(file, fileList) {
      this.handleUpload(file, fileList, 'img')
    },
    handleUpload(file, fileList, type){
      if(fileList.length == 0){
        return
      } else {
        const formData = new FormData();
        formData.append("file", fileList[0].raw)
        upload(formData).then(response => {
          this.$modal.msgSuccess(response.msg);
          if (type === 'img') {
            this.form.scaleImg = response.url
          } else {
            this.form.scaleImg = response.url
          }
        })
      }
    },
    // 大图预览
    showPicture (row) {
      this.evaluatePictureList.push(row)
    },

    // 获取所有的类型
    getAllTypes() {
      let query = '{"mchId": 1}'
      allType(query).then(response => {
        if (response.code == 200) {
          for (let type of response.data) {
            console.log(type);
            if (type.childs == null) {
              this.types.push(type);
            } else {
              for (let child of type.childs) {
                this.types.push(child);
              }
            }
          }
        }
      })
    },
  },
};
</script>
